class autoResize {

  dom = null

  width = 0

  height = 0

  debounceInitWHFun = ''

  domObserver = ''

  allWidth = 0

  constructor(dom = null) {
    this.dom = dom
    this.autoResizeMixinInit()
  }

  autoResizeMixinInit() {

    this.initWH(false)

    this.getDebounceInitWHFun()

    this.bindDomResizeCallback()

    this.afterAutoResizeMixinInit()
  }

  initWH(resize = true) {
    const dom = this.dom

    this.width = dom ? dom.clientWidth : 0
    this.height = dom ? dom.clientHeight : 0

    if (!dom) {
      console.warn('DataV: Failed to get dom node, component rendering may be abnormal!')
    } else if (!this.width || !this.height) {
      console.warn('DataV: Component width or height is 0px, rendering abnormality may occur!')
    }

    if (resize) this.onResize()
  }

  getDebounceInitWHFun() {
    this.debounceInitWHFun = debounce(100, this.initWH)
  }

  bindDomResizeCallback() {

    this.domObserver = observerDomResize(this.dom, this.initWH)

    window.addEventListener('resize', this.initWH)
  }

  unbindDomResizeCallback() {

    if (!this.domObserver) return

    this.domObserver.disconnect()
    this.domObserver.takeRecords()
    this.domObserver = null

    window.removeEventListener('resize', this.debounceInitWHFun)
  }

  afterAutoResizeMixinInit() {

    this.initConfig()

    this.setAppScale()

  }

  initConfig() {
    this.allWidth = this.width
    const { width, height } = screen
    this.dom.style.width = `${width}px`
    this.dom.style.height = `${height}px`
  }

  setAppScale() {

    const currentWidth = document.body.clientWidth

    this.dom.style.transform = `scale(${currentWidth / this.allWidth})`
  }

  onResize() {
    this.setAppScale()
  }

}

function debounce(delay, callback) {
  let lastTime

  return function() {
    clearTimeout(lastTime)

    const [that, args] = [this, arguments]

    lastTime = setTimeout(() => {
      callback.apply(that, args)
    }, delay)
  }
}

function observerDomResize(dom, callback) {
  const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver

  const observer = new MutationObserver(callback)

  observer.observe(dom, { attributes: true, attributeFilter: ['style'], attributeOldValue: true })

  return observer
}

export { autoResize }
